<template>
   <div>
        <Button type="primary" @click="openCropperModal">上传图片</Button>

        <Modal
            :value="uploadDialogVisible"
            :title="dialogTitle"
            :mask-closable="maskClosable"
            ok-text="确认"
            cancel-text="取消"
            width="1200"
            @on-ok="finish"
            @on-cancel="uploadDialogVisible = false" class="cropper-modal">

            <!-- 截图开始 -->
            <Row>
                <Col span="24">
                    <div class="test-button">

                        <label class="btn" v-bind:for="cropperId">上传文件</label>
                        <input type="file" v-bind:id="cropperId" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event)">
                        <a @click="down" class="btn">下载</a>

                        <!-- <a @click="fixedProportion" class="btn">固定比例</a> -->
                        <a @click="leftRotateImg" class="btn">向左旋转</a>
                        <a @click="rightRotateImg" class="btn">向左旋转</a>
                    </div>
                </Col>
            </Row>

            <Row>
                <Col span="24">
                    <Col span="12">
                        <div style="height: 350px;">
                            <vueCropper
                              ref="cropper"
                              :img="option.img"
                              :outputSize="option.size"
                              :outputType="option.outputType"
                              :info="true"
                              :fixed="fixed"
                              :fixedNumber="fixedNumber"
                              @realTime="realTime">
                            </vueCropper>
                        </div>
                    </Col>
                    <Col span="12">
                        <div class="show-preview" :style="{'width': previews.w + 'px', 'height': previews.h + 'px',  'overflow': 'hidden', 'margin': '5px'}">
                            <div :style="previews.div">
                                <img :src="option.img" :style="previews.img">
                            </div>
                        </div>
                    </Col>
                </Col>

            </Row>

            <!-- 截图结束 -->

        </Modal>

    </div>


</template>
<script>
    //import vueCropper from './vue-cropper'
    //这里使用cnpm在线的截图工具,本地版本不能旋转图片
    import vueCropper from 'vue-cropper';
    import $ from 'jquery';
    export default {
        props: {
            //组件id
            cropperId: {
                type: String,
                default: ''
            },
            //编辑时展示的图片url
            imageSrc: {
                type: String,
                default: ''
            },
            //高度
            imageHeight : {
                type: String,
                default: '0'
            },
            //宽度
            imageWidth : {
                type: String,
                default: '0'
            },
            //模态框标题
            dialogTitle : {
                type: String,
                default: '上传图片'
            },
            //是否开启宽度和高度比例
            fixed : {
                type: Boolean,
                default: false
            },
            //比例大小
            fixedNumber: {
                type: Array,
                default: function () {
                    return [4, 3]
                }
            }
        },
        //监控内容变化
        watch: {
            uploadDialogVisible(val, oldval) {
                if (val == true) {
                    var imageUrl = this.imageSrc;
                    if (null != imageUrl && '' != imageUrl && 'undefined' != imageUrl) {
                        imageUrl = '/ws/img/view/'+imageUrl;
                    }
                    this.option.img = imageUrl;
                }
            }
        },
        data() {
            return {
                //截图模态框状态(默认为false)
                uploadDialogVisible:false,
                //是否允许点击遮罩层关闭
                maskClosable:false,
                //是否开始截取(默认false)
                crap: true,
                //预览对象
                previews: {},
                //参数
                option: {
                  img: '',
                  size: 0.8,
                  //此处必须设为png,不然空余部分会变成黑色
                  outputType: 'png',
                  name:'',
                  // 开启宽度和高度比例
                  // fixed:true,
                  // fixedNumber:[4, 3]
                },
                //下载
                downImg: '#',

            }
        },
        //注册局部组件 
        components:{
            vueCropper
        },
        //初始化方法
        mounted() {

        }, 
        methods: {
            //固定比例
            fixedProportion(){
                this.option.fixed = !this.option.fixed;
            },
            //打开截图模态框
            openCropperModal(){
                $(".cropper-modal .ivu-modal-mask").css("z-index","1110");
                $(".cropper-modal .ivu-modal-wrap").css("z-index","1111"); 
                this.uploadDialogVisible = true;
            },
            //上传图片
            uploadImg (e) {
              //上传图片
              // this.option.img
              var file = e.target.files[0];

              if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
                 alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
                 return false
               }

              var reader = new FileReader()
              reader.onload = (e) => {
                //设置图片或者图片url
                this.option.img = e.target.result;
                this.option.name = file.name.replace(',','');
                this.startCrop();
              }
              reader.readAsDataURL(file);
              //解决第一次上传成功后第二次相同文件不触发上传事件
              e.target.value='';
            },
            //开始截取
            startCrop () {
              // start
              this.crap = true;
              this.$refs.cropper.startCrop();
            },
            //停止截取
            stopCrop () {
              //  stop
              this.crap = false;
              this.$refs.cropper.stopCrop();
            },
            //清除截取
            clearCrop () {
                // clear
                this.$refs.cropper.clearCrop();
            },
            // 实时预览函数
            realTime (data) {
              this.previews = data;
            },
            //预览
            viewImage(){
                 // 输出
                var test = window.open('about:blank')
                test.document.body.innerHTML = '图片生成中..'
                this.$refs.cropper.getCropData((data) => {
                    test.location.href = data;
                });
            },
            //完成
            finish () {
                this.$refs.cropper.getCropData((data) => {
                    this.option.img = data;
                    this.uploadImgData();
                });
                this.uploadDialogVisible = false;
            },
            //旋转图片
            leftRotateImg(){
                this.$refs.cropper.rotateLeft();
            },
            //旋转图片
            rightRotateImg(){
                this.$refs.cropper.rotateRight();
            },
            //下载
            down () {
                var aLink = document.createElement('a');
                aLink.download = 'demo';
                // 输出
                this.$refs.cropper.getCropData((data) => {
                    this.downImg = data;
                    aLink.href = data;
                    aLink.click();
                });
            },
            //上传图片到服务器
            uploadImgData(){
                var data = {imageName:this.option.name,imageData:this.option.img};
                const _this = this;
                this.axios.post('/ws/batch/uploadBase64Img',data).then(response => {
                    let res = response.data;
                    if (res.meta.code==0) {
                      if(res.data.code==0){
                        _this.$emit('uploadSuccessEvent', res.data.fileList[0].fileId);
                      }else{
                        _this.$message.error(res.data.message);  
                      }
                    }else if(res.meta.code==1){
                      _this.$message.error(res.meta.message);
                    }else{
                      _this.$message.error("上传失败");
                    }
                });
            }
            
        }
    }
</script>
<style type="text/css">
        
    
    .ivu-modal-content {
        border-radius: 0px!important;
    }
    
    .test-button {
        display: flex;
        flex-wrap: wrap;
    }

    .btn {
        display: inline-block;
        line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    background: #fff;
    border: 1px solid #c0ccda;
    color: #1f2d3d;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 0px 10px 10px 0px;
    padding: 9px 15px;
    font-size: 14px;
    border-radius: 4px;
    color: #fff;
    background-color: #50bfff;
    border-color: #50bfff;
    transition: all .2s ease;
        text-decoration: none;
        user-select: none;
    }

    .upload-main-div{
        /*width: 100%;*/
        height: 500px;
    }

    .content {
        margin: auto;
        max-width: 1200px;
        margin-bottom: 100px;
    }

    .des {
        line-height: 30px;
    }

    code.language-html {
        padding: 10px 20px;
        margin: 10px 0px;
        display: block;
        background-color: #333;
        color: #fff;
        overflow-x: auto;
        font-family: Consolas, Monaco, Droid, Sans, Mono, Source, Code, Pro, Menlo, Lucida, Sans, Type, Writer, Ubuntu, Mono;
        border-radius: 5px;
        white-space: pre;
    }

    .show-info {
        margin-bottom: 50px;
    }

    .show-info h2 {
        line-height: 50px;
    }

    @keyframes slide {
    0%  {
      background-position: 0 0;
    }
    100% {
      background-position: -100% 0;
    }
  }


</style>

